package cdc.cs.service;

import cdc.cs.config.ODataConfig;
import cdc.cs.entity.SuppliersVO;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @ClassName: ODataSuppliersService
 * @Description: TODO
 * @Author: kevin
 * @Date: 2020/5/8 10:25
 * @Version: 1.0
 */
@Service
public class ODataSuppliersService {

    public JSONObject dataChange(SuppliersVO suppliersVO) {
        JSONObject result = new JSONObject();
        result.put("Supplier", suppliersVO.getSupplier());
        result.put("AlternativePayeeAccountNumber", suppliersVO.getAlternativePayeeAccountNumber());
        result.put("AuthorizationGroup", suppliersVO.getAuthorizationGroup());
        result.put("CreatedByUser", suppliersVO.getCreatedByUser());
        result.put("CreationDate", suppliersVO.getCreationDate());
        result.put("Customer", suppliersVO.getCustomer());
        result.put("PostingIsBlocked", suppliersVO.getPostingIsBlocked());
        result.put("SupplierAccountGroup", suppliersVO.getSupplierAccountGroup());
        result.put("SupplierFullName", suppliersVO.getSupplierFullName());
        result.put("SupplierName", suppliersVO.getSupplierName());
        result.put("BirthDate", suppliersVO.getBirthDate());
        result.put("ConcatenatedInternationalLocNo", suppliersVO.getConcatenatedInternationalLocNo());
        result.put("DeletionIndicator", suppliersVO.getDeletionIndicator());
        result.put("FiscalAddress", suppliersVO.getFiscalAddress());
        result.put("Industry", suppliersVO.getIndustry());
        result.put("InternationalLocationNumber1", suppliersVO.getInternationalLocationNumber1());
        result.put("InternationalLocationNumber2", suppliersVO.getInternationalLocationNumber2());
        result.put("InternationalLocationNumber3", suppliersVO.getInternationalLocationNumber3());
        result.put("IsNaturalPerson", suppliersVO.getIsNaturalPerson());
        result.put("ResponsibleType", suppliersVO.getResponsibleType());
        result.put("SuplrQltyInProcmtCertfnValidTo", suppliersVO.getSuplrQltyInProcmtCertfnValidTo());
        result.put("SuplrQualityManagementSystem", suppliersVO.getSuplrQualityManagementSystem());
        result.put("SupplierCorporateGroup", suppliersVO.getSupplierCorporateGroup());
        result.put("SupplierProcurementBlock", suppliersVO.getSupplierProcurementBlock());
        result.put("TaxNumber1", suppliersVO.getTaxNumber1());
        result.put("TaxNumber2", suppliersVO.getTaxNumber2());
        result.put("TaxNumber3", suppliersVO.getTaxNumber3());
        result.put("TaxNumber4", suppliersVO.getTaxNumber4());
        result.put("TaxNumber5", suppliersVO.getTaxNumber5());
        result.put("TaxNumberResponsible", suppliersVO.getTaxNumberResponsible());
        result.put("TaxNumberType", suppliersVO.getTaxNumberType());
        result.put("SuplrProofOfDelivRlvtCode", suppliersVO.getSuplrProofOfDelivRlvtCode());
        result.put("BR_TaxIsSplit", suppliersVO.getBRTaxIsSplit());
        return result;
    }

    public void supplierAddOne(SuppliersVO suppliersVO) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(ODataConfig.bankOne);
        httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
        // 解决中文乱码问题
        JSONObject jsonObject = dataChange(suppliersVO);
        StringEntity stringEntity = new StringEntity(jsonObject.toString(), "UTF-8");
        stringEntity.setContentEncoding("UTF-8");
        httpPost.setEntity(stringEntity);
        /* System.out.println("Executing request " + httpPost.getRequestLine()); **/
        ResponseHandler<String> responseHandler = response -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("数据发送异常: " + status);
            }
        };
        httpclient.execute(httpPost, responseHandler);
}

    /**
     * 获取供应商总数
     * @return
     * @throws IOException
     */
    public String supplierGetAll() throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(ODataConfig.bankOne + "/$count");
        ResponseHandler<String> responseHandler = response -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("数据发送异常: " + status);
            }
        };
        String responseBody = httpclient.execute(httpget, responseHandler);
        System.out.println(responseBody);
        return responseBody;
    }

//    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void supplierUpdateOne(String id, SuppliersVO suppliersVO) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(ODataConfig.bankOne + "('" + id + "')");
        httpPut.addHeader("Content-Type", "application/json;charset=UTF-8");
        // 解决中文乱码问题
        JSONObject jsonObject = dataChange(suppliersVO);
        StringEntity stringEntity = new StringEntity(jsonObject.toString(), "UTF-8");
        stringEntity.setContentEncoding("UTF-8");
        httpPut.setEntity(stringEntity);
        ResponseHandler<String> responseHandler = response -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("数据发送异常: " + status);
            }
        };
        httpclient.execute(httpPut, responseHandler);
    }

    public void supplierDeleteOne(String id) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpDelete httpDelete = new HttpDelete(ODataConfig.bankOne + "('" + id + "')");
        ResponseHandler<String> responseHandler = response -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("数据发送异常: " + status);
            }
        };
        httpclient.execute(httpDelete, responseHandler);
    }

    /**
     * 获取单个供应商
     * @return
     * @throws IOException
     */
    public Object supplierGetOne(String id) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(ODataConfig.bankOne + "('" + id + "')?$format=json");
        ResponseHandler<String> responseHandler = response -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("数据发送异常: " + status);
            }
        };
        String responseBody = httpclient.execute(httpget, responseHandler);
        Object result = JSONObject.parse(responseBody);
        return result;
    }
}
